<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  -->
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表区域  -->
      <el-table :data="RolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 定义作用域插槽 -->
          <template slot-scope="scope">
            <!-- v-for循环数据 -->
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级三级权限 -->
                <!-- if 判断实现添加类属性 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :keq="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3, i3) in item2.children" :keq="item3.id" closable @close="removeRightById(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--分配权限 dialog  -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- Tree 树形控件 -->
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 对话框-->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible" width="50%">
      <el-form ref="addRolesref" :model="addRolesFrom" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="addRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 对话框-->
    <el-dialog title="编辑角色" :visible.sync="editRolesDialogVisible" width="50%">
      <el-form ref="editformref" :model="editRolesFrom" label-width="80px">
        <el-form-item label="角色Id:">
          <el-input v-model="editRolesFrom.roleId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称:">
          <el-input v-model="editRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:">
          <el-input v-model="editRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 角色列表
      RolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        // 绑定label
        label: "authName",
        // 绑定children
        children: "children",
        // 默认选中的节点id值
      },
      // 默认选中的节点id值
      defKeys: [],
      // 当前即将分配角色权限的id
      roleId: "",
      // 添加角色
      addRolesDialogVisible: false,
      addRolesFrom: {
        roleName: "",
        roleDesc: "",
      },
      // 编辑角色对话框展示事件
      editRolesDialogVisible: false,
      // 编辑角色数据
      editRolesFrom: {
        roleId:"",
        roleName: "",
        roleDesc: "",
      },
    };
  },
  // 生命周期函数
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      } else {
        this.RolesList = res.data;
        console.log(this.RolesList);
        return this.$message.success("获取角色列表成功！");
      }
    },
    // 根据id删除权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      // 如果确认删除返回字符串confirm
      // 如果取消了删除返回值为 cancel
      console.log(confirmResult);
      if (confirmResult === "cancel") {
        this.$message.info("取消了删除！");
      } else {
        // 1.5.7. 删除角色指定权限
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
        console.log(role.id);
        console.log(rightId);
        if (res.meta.status !== 200) {
          this.$message.error("删除权限失败！");
        } else {
          role.children = res.data;
          this.$message.success("确认删除！");
        }
      }
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id;
      // 获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        this.$message.error("获取权限列表数据失败!");
      } else {
        this.$message.success("获取权限列表数据成功!");
        this.rightList = res.data;
        console.log(this.rightList);
        //调用getLeafKeys进行递归，将三级权限添加到数组中
        this.getLeafKeys(role, this.defKeys);
      }
      //当点击分配权限按钮时，展示对应的对话框
      this.setRightDialogVisible = true;
    },
    getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      if (!node.children) {
        //如果当前节点不包含children属性，则表示node为三级权限
        return arr.push(node.id);
      }
      //递归调用
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 监听关闭事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    //当用户在树形权限对话框中点击确定，将用户选择的
    //权限发送请求进行更新
    async allotRights() {
      //获取所有选中及半选的内容
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
      //将数组转换为 , 拼接的字符串
      const idStr = keys.join(",");
      //发送请求完成更新
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr });
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败!");
      } else {
        this.$message.success("分配权限成功!");
        this.getRolesList();
      }
      //关闭对话框
      this.setRightDialogVisible = false;
    },
    // 添加角色
    async addRoles() {
      const { data: res } = await this.$http.post("roles", this.addRolesFrom);
      if (res.meta.status !== 201) {
        return this.$message.error("添加角色失败!");
      } else {
        this.getRolesList();
        this.$message.success("添加角色成功！");
        this.addRolesDialogVisible = false;
      }
    },
    // 删除角色警告框
    async removeRoleById(roleId) {
      // messagebox
      console.log(roleId);
      const confirmResult = await this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => {
        return err;
      });
      // 如果确认删除返回字符串confirm
      // 如果取消了删除返回值为 cancel
      console.log(confirmResult);
      if (confirmResult === "cancel") {
        this.$message.info("取消了删除！");
      } else {
        const { data: res } = await this.$http.delete(`roles/${roleId}`);
        if (res.meta.status !== 200) {
          this.$message.error("删除用户失败！");
        } else {
          this.getRolesList();
          this.$message.success("确认删除！");
        }
      }
    },
    // 展示编辑角色对话框
    async showEditDialog(roleId) {
      const { data: res } = await this.$http.get(`roles/${roleId}`);
      if (res.meta.status !== 200) {
        this.$message.error("角色信息查询失败！");
      } else {
        this.editRolesFrom = res.data;
        this.$message.success("角色信息查询成功！");
        this.editRolesDialogVisible = true;
      }
    },
    // 编辑角色并提交
    async editRoles() {
      const { data: res } = await this.$http.put("roles/" + this.editRolesFrom.roleId, { roleName: this.editRolesFrom.roleName, roleDesc: this.editRolesFrom.roleDesc });
      if(res.meta.status!==200){
        this.$message.error("修改角色信息失败！");
      }else{
        // 关闭对话框
            this.editRolesDialogVisible = false;
            // 刷新列表
            this.getRolesList();
            // 显示修改成功信息
            this.$message.success("修改角色信息成功！");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  // 上边框
  border-top: 1px solid rgba(26, 24, 24, 0.2);
}
.bdbottom {
  // 底边框
  border-bottom: 1px solid rgba(26, 24, 24, 0.2);
}
.vcenter {
  // 居中
  display: flex;
  align-items: center;
}
</style>
